package com.yhj.reggie.service.impl;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.yhj.reggie.entity.Category;
import com.yhj.reggie.entity.Page;
import com.yhj.reggie.entity.Setmeal;
import com.yhj.reggie.exception.BusinessException;
import com.yhj.reggie.mapper.CategoryMapper;
import com.yhj.reggie.mapper.DishMapper;
import com.yhj.reggie.mapper.SetmealMapper;
import com.yhj.reggie.service.CategoryService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.List;

@Service
public class CategoryServiceImpl implements CategoryService {

    @Autowired(required = false)
    private CategoryMapper categoryMapper;

    @Autowired(required = false)
    private DishMapper dishMapper;

    @Autowired(required = false)
    private SetmealMapper setmealmapper;

    @Override
    public Boolean save(Category category) {

        category.setCreateTime(LocalDateTime.now());
        category.setUpdateTime(LocalDateTime.now());


        Category categoryDB = categoryMapper.findByName(category.getName());
        if (categoryDB !=null){
            throw new BusinessException("名称已存在,请修改");
        }


        return categoryMapper.save(category)>0;
    }

    /**
     * 分页查询
     *
     * @param page
     * @param pageSize
     * @return
     */
    @Override
    public Page<Category> findByPage(Integer page, Integer pageSize) {
        PageHelper.startPage(page,pageSize);
        List<Category> categoryList = categoryMapper.findByPage();
        PageInfo<Category> categoryPageInfo = new PageInfo<>(categoryList);

        Page<Category> resultPage = new Page<>();
        resultPage.setRecords(categoryPageInfo.getList());
        resultPage.setTotal(categoryPageInfo.getTotal());

        return resultPage;
    }

    /**
     * 删除
     *
     * @param id
     * @return
     */
    @Override
    public Boolean delete(Long id) {
        if (dishMapper.countByCid(id)>0){
            throw new BusinessException("该类别有菜式,请先清空菜式");
        }
        if (setmealmapper.countByCid(id)>0){
            throw new BusinessException("该类别有套餐,请先清空套餐");
        }

        return categoryMapper.delete(id)>0;
    }

    /**
     * 修改
     *
     * @param category
     * @return
     */
    @Override
    public Boolean update(Category category) {
        Category byNameE = categoryMapper.findByNameE(category);
        if(byNameE != null){
            throw new BusinessException("已存在同名分类,修改失败");
        }
        category.setUpdateTime(LocalDateTime.now());

        return categoryMapper.update(category)>0;
    }

    /**
     * 根据type查询分类列表数据
     *
     * @param type
     * @return
     */
    @Override
    public List<Category> findAllByType(Integer type) {

        return categoryMapper.findAllByType(type);
    }
}
